﻿using System;
using System.Messaging;
using System.Threading;

namespace PSE.Communication.Fix.Common
{
    public class FixQueue
    {
        private MessageQueue _queue;
        private int _count;
        private object _lock;
        private XmlMessageFormatter _xmlMessageFormatter;

        public int Count
        {
            get { return _count; }
            set { _count = value; }
        }

        public FixQueue(string queueName)
        {
            if (!MessageQueue.Exists(queueName))
                throw new Exception(string.Format("The queue with name '{0}' does not exist.", queueName));

            _lock = new object();
            _queue = new MessageQueue(queueName);
            _xmlMessageFormatter = new XmlMessageFormatter(new String[] { "System.String, mscorlib" });

            GetQueueSize();
        }

        public void Enqueue(string label, object message)
        {
            lock (_lock)
            {
                _queue.Send(new Message() { Body = message, Label = label });
                _count++;
            }
        }

        public Message Dequeue()
        {
            lock (_lock)
            {
                Message m = _queue.Receive();
                m.Formatter = _xmlMessageFormatter;
                _count--;
                return m;
            }
        }

        public Message Peek()
        {
            lock (_lock)
            {
                Message m = _queue.Peek();
                m.Formatter = _xmlMessageFormatter;
                return m;
            }
        }

        private void GetQueueSize()
        {
            _count = 0;

            MessageEnumerator enumerator = _queue.GetMessageEnumerator2();

            while (enumerator.MoveNext())
            {
                _count++;
            }
        }
    }
}